﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Application.ManageUserTable;
using wt.wine.Domain.Entities;

namespace wt.wine.Infrastructure.Persistence.Repository
{
    public class UserdevicetableRepository : IUserdevicetableRepository
    {
        private readonly IApplicationDbContext _dbcontext;
        public UserdevicetableRepository(IApplicationDbContext dbcontext)
        {
            _dbcontext = dbcontext;
        }

        /// <summary>
        /// 添加员工的时候，绑定设备
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="adduserid"></param>
        /// <param name="list_deviceid"></param>
        /// <param name="cancellationtoken"></param>
        /// <returns></returns>
        public async Task EditUserDevices(int userid, int adduserid, List<devicetable> list_deviceid, CancellationToken cancellationtoken)
        {
            var list = await _dbcontext.userdevicetable.AsNoTracking().Where(p => p.binduserid == adduserid && p.deviceid > 0).ToListAsync();
            List<devicetable> list_deviceid_add = new List<devicetable>() { };
            List<userdevicetable> list_add = new List<userdevicetable>();
            if (list != null && list.Any())
            {
                for (int i = 0; i < list.Count(); i++)
                {
                    if (list_deviceid.Where(p => p.id == list[i].deviceid).Count() > 0)
                    {
                        if (list[i].state == -1)
                        {
                            list[i].state = 1;
                            _dbcontext.Entry<userdevicetable>(list[i]).Property("state").IsModified = true;
                        }
                    }
                    else
                    {
                        list[i].state = -1;
                        _dbcontext.Entry<userdevicetable>(list[i]).Property("state").IsModified = true;
                    }
                }
                List<int> list_added = list.Where(p=>p.state>=0).Select(p => p.deviceid).ToList();
                if (list_add != null && list.Count() > 0)
                {
                    list_deviceid_add = list_deviceid.Where(p => !list_added.Contains(p.id)).ToList();
                }

            }
            else
            {
                list_deviceid_add = list_deviceid;
            }

            if (list_deviceid_add != null && list_deviceid_add.Any())
            {
                for (int i = 0; i < list_deviceid_add.Count(); i++)
                {
                    list_add.Add(new userdevicetable()
                    {
                        userid = userid,
                        userpid = userid,
                        binduserid = adduserid,
                        state = 0,
                        createtime = DateTime.Now,
                        updatetime = DateTime.Now,
                        deviceid = list_deviceid_add[i].id,
                        skuid = list_deviceid_add[i].skuid,
                        remark = ""
                    });
                }
            }

            if (list_add != null && list_add.Any())
            {
                await _dbcontext.userdevicetable.AddRangeAsync(list_add, cancellationtoken);
            }
            await _dbcontext.SaveChangesAsync(cancellationtoken);
        }

        public async Task<List<GetUserTableDeviceList>> GetUserTableDeviceList(List<int> list_userid, CancellationToken cancellationtoken)
        {
            return await (from u in _dbcontext.userdevicetable.AsNoTracking().Where(p => list_userid.Contains(p.binduserid) && p.state >= 0)
                          from d in _dbcontext.devicetable.AsNoTracking().Where(p => p.id == u.deviceid && p.state >= 0 && p.skuid >= 0)
                          where d.id > 0
                          select new GetUserTableDeviceList()
                          {
                              id = d.id,
                              cusdeviceid = d.deviceid,
                              deviceid = d.deviceid,
                              userid = u.binduserid,
                              skuname = _dbcontext.skutable.AsNoTracking().Where(p => p.id == d.skuid).Select(p => p.name).FirstOrDefault()
                          }
                    ).ToListAsync(cancellationtoken);
        }


        public async Task<List<GetUserTableDeviceList>> GetUserTableDeviceListByAdmin(int userid, CancellationToken cancellationtoken)
        {
            return await (
                          from d in _dbcontext.devicetable.AsNoTracking().Where(p => p.binduserid == userid && p.state >= 0)
                          select new GetUserTableDeviceList()
                          {
                              id = d.id,
                              cusdeviceid = d.deviceid,
                              deviceid = d.deviceid,
                              userid = d.binduserid,
                              skuname = _dbcontext.skutable.AsNoTracking().Where(p => p.id == d.skuid).Select(p => p.name).FirstOrDefault()
                          }
                    ).ToListAsync(cancellationtoken);
        }
    }
}
